var express = require('express')
var router = express.Router()
var dbHelper = require('../db/dbHelper')
var User = require('./../models/user')
// 注册中间件
router.post('/signUp', function (req, res, next) {
  console.log('Add user')
  dbHelper.addUser(req.body, function (success, doc) {
    res.send(doc)
  })
})

// 登录中间件
router.post('/signIn', function (req, res, next) {
  dbHelper.findUser(req, function (success, doc) {
    // console.log(req.session.username)
    // console.log(doc)
    res.send(doc)
  })
})
//获取全部用户信息
router.get('/users', function (req, res) {
  User.find({})
    .then(user => {

      res.json(user)
    })
    .catch(err => {
      res.json(err)
    })
})
//删除用户信息
router.delete('/users/:id', function (req, res) {
  User.findByIdAndRemove({
    _id: req.params.id
  })
    .then(user => res.send(`${mousers.username}删除成功`))
    .catch(err => res.json(err))
})
//修改用户的一个信息
router.post('/users/:username', function (req, res) {
  User.findOneAndUpdate({ username: decodeURI(req.params.username) },
    {
      $set: {
        email: req.body.email,
        qq: req.body.qq,
        mobilePhone: req.body.mobilePhone,
        introduction: req.body.introduction,

      }
    }, {
      new: true

    })
    .then(user => res.json(user))
    .catch(err => res.json(err))
})
/*router.get('/message/:id', (req, res) => {
  Message.findById(req.params.id)
    .then(message => {
      res.json(message)
    })
    .catch(err => {
      res.json(err)
    })
}) */
//获得一个用户的资料 //返回一个文档
router.get('/users/:username', function (req, res) {
  User.findOne({ username: decodeURI(req.params.username) })
    .then(user => {
      res.json(user)


    })
    .catch(err => {
      res.json(err)
    })


})
module.exports = router